package domo1.utils;

import com.mysql.cj.jdbc.MysqlDataSource;

import javax.sql.DataSource;
import java.sql.Connection;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;

public class DButils {
    //创建数据源
    private static DataSource dataSource=null;
    private  static final String URL="jdbc:mysql://127.0.0.1:3306/java?characterEncoding" + "=utf8&allowPublicKeyRetrieval=true&useSSL=false";
    private static final String USER="root";
    private static final  String PASSWORD="123456";
    static {
        MysqlDataSource mysqlDataSource=new MysqlDataSource();
        mysqlDataSource.setURL(URL);
        mysqlDataSource.setUser(USER);
        mysqlDataSource.setPassword(PASSWORD);
        dataSource=mysqlDataSource;
    }
    //获取数据库连接
    public static Connection geconnecton() throws SQLException {
      return dataSource.getConnection();
    }
    //关闭数据库连接
    public static void close(ResultSet resultSet, Statement statement,Connection connection){
            //释放结果集
            if (resultSet != null) {
                try{
                    resultSet.close();
                }
                catch (SQLException e){
                    e.printStackTrace();
                }
            }
            //释放statement
            if (statement !=null){
                try {
                    statement.close();
                }
                catch (SQLException e){
                    e.printStackTrace();
                }
            }
            //断开连接
            if (connection !=null){
                try {
                    connection.close();
                }
                catch (SQLException e){
                    e.printStackTrace();
                }
            }
    }
    //构造方法私有化, 防止new这个对象
    private DButils(){};
}
